<template>
  <div class="edit-course">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>编辑课程</h3>
        </div>
      </template>

      <el-form
          ref="formRef"
          :model="formData"
          :rules="rules"
          label-width="110px"
      >
        <!-- 课程名称 -->
        <el-form-item label="课程名称" prop="courseName">
          <el-input
              v-model="formData.courseName"
              placeholder="请输入课程名称"
          />
        </el-form-item>

        <!-- 课程代码 -->
        <el-form-item label="课程代码" prop="courseCode">
          <el-input
              v-model="formData.courseCode"
              placeholder="请输入课程代码"
              disabled
          />
        </el-form-item>

        <!-- 开课时间 -->
        <el-form-item label="开课时间" prop="startTime">
          <el-date-picker
              v-model="formData.startTime"
              type="datetime"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择开课时间"
              style="width: 100%"
          />
        </el-form-item>

        <!-- 最大选课人数 -->
        <el-form-item label="最大选课人数" prop="maxStudents">
          <el-input-number
              v-model="formData.maxStudents"
              :min="1"
              placeholder="请输入最大人数"
          />
        </el-form-item>

        <!-- 是否公开 -->
        <el-form-item label="是否公开" prop="isPublic">
          <el-switch
              v-model="formData.isPublic"
              active-value="true"
              inactive-value="false"
          />
        </el-form-item>

        <!-- 课程描述 -->
        <el-form-item label="课程描述" prop="description">
          <el-input
              v-model="formData.description"
              type="textarea"
              :rows="4"
              placeholder="请输入课程描述"
          />
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card style="margin-top: 24px">
      <template #header>
        <div class="card-header">
          <h3>课程详情（章节管理）</h3>
          <el-button type="primary" @click="addChapter">新增章节</el-button>
        </div>
      </template>
      <el-table :data="chapters" style="width: 100%; margin-top: 10px">
        <el-table-column prop="chapterName" label="章节名称"/>
        <el-table-column prop="content" label="内容"/>
        <el-table-column prop="videoUrl" label="视频链接"/>
        <el-table-column prop="attachmentUrl" label="附件链接"/>
        <el-table-column label="操作">
          <template #default="{ row, $index }">
            <el-button size="small" @click="editChapter(row, $index)"
            >编辑
            </el-button
            >
            <el-button size="small" type="danger" @click="removeChapter($index)"
            >删除
            </el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog v-model="chapterDialogVisible" title="编辑章节">
      <el-form :model="chapterForm" :rules="chapterFormRules">
        <el-form-item label="章节名称" prop="chapterName">
          <el-input v-model="chapterForm.chapterName"/>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input type="textarea" v-model="chapterForm.content"/>
        </el-form-item>
        <el-form-item label="视频链接" prop="videoUrl">
          <el-input v-model="chapterForm.videoUrl"/>
        </el-form-item>
        <el-form-item label="附件链接" prop="attachmentUrl">
          <el-input v-model="chapterForm.attachmentUrl"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="chapterDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveChapter">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from "vue";
import {useRouter, useRoute} from "vue-router";
import {ElMessage} from "element-plus";
import {courseApi} from "../../api/courseApi";

const router = useRouter();
const route = useRoute();
const formRef = ref(null);

// 表单数据
const formData = reactive({
  courseName: "",
  courseCode: "",
  startTime: "",
  maxStudents: 1,
  isPublic: "false",
  description: "",
});

// 表单验证规则
const rules = {
  courseName: [
    {required: true, message: "请输入课程名称", trigger: "blur"},
    {min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur"},
  ],
  startTime: [{required: true, message: "请选择开课时间", trigger: "change"}],
  maxStudents: [
    {required: true, message: "请输入最大选课人数", trigger: "blur"},
  ],
  isPublic: [{required: true, message: "请选择是否公开", trigger: "change"}],
};

const chapterFormRules = {
  chapterName: [{required: true, message: "请输入章节名称", trigger: "blur"}],
  content: [{required: true, message: "请输入内容", trigger: "blur"}],
  // videoUrl: [{ required: true, message: "请输入视频链接", trigger: "blur" }],
  // attachmentUrl: [
  //   { required: true, message: "请输入附件链接", trigger: "blur" },
  // ],
};
// 获取课程详情
const getChapter = async () => {
  try {
    const res = await courseApi.getChapter(route.params.id);
    const data = res.result;
    Object.assign(formData, data);
    // 更新表单数据
    Object.assign(formData, {
      isPublic: data.isPublic ? "true" : "false",
    });
  } catch (error) {
    console.error("获取课程详情失败:", error);
  }
};

// 提交表单
const handleSubmit = async () => {
  try {
    await courseApi.updateCourse(formData);
    ElMessage.success("修改课程成功");
    router.push("/course/list");
  } catch (error) {
    console.error("修改课程失败:", error);
  }
};

// 取消
const handleCancel = () => {
  router.back();
};

const chapters = ref([]); // 课程详情章节数组
const chapterDialogVisible = ref(false);
const chapterForm = reactive({
  chapterName: "",
  content: "",
  videoUrl: "",
  attachmentUrl: "",
});
let editingIndex = -1;

// 加载课程详情章节
const loadChapters = async () => {
  try {
    const res = await courseApi.getChapters(route.params.id);
    chapters.value = res.result;
  } catch (error) {
    console.error("加载课程章节失败:", error);
  }
};

function addChapter() {
  editingIndex = -1;
  Object.assign(chapterForm, {
    chapterName: "",
    content: "",
    videoUrl: "",
    attachmentUrl: "",
  });
  chapterDialogVisible.value = true;
}

function editChapter(row, index) {
  editingIndex = index;
  Object.assign(chapterForm, row);
  chapterDialogVisible.value = true;
}

async function saveChapter() {
  // 保存章节
  try {
    await courseApi.addChapter({
      courseId: route.params.id,
      chapterName: chapterForm.chapterName,
      content: chapterForm.content,
      videoUrl: chapterForm.videoUrl,
      attachmentUrl: chapterForm.attachmentUrl,
    });
    ElMessage.success("章节保存成功");
    loadChapters();
    chapterDialogVisible.value = false;
  } catch (error) {
    ElMessage.error("章节保存失败");
  }
}

async function removeChapter(index) {
  const detail = chapters.value[index];
  if (detail && detail.chapterId) {
    try {
      await courseApi.deleteChapter(detail.chapterId);
      ElMessage.success("章节删除成功");
      loadChapters();
    } catch (error) {
      ElMessage.error("章节删除失败");
    }
  } else {
    chapters.value.splice(index, 1);
  }
}

onMounted(() => {
  getChapter();
  loadChapters();
});
</script>

<style scoped>
.edit-course {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
